/*
 * @Author: gyc
 * @Date: 2020-06-11 15:50:10
 * @LastEditTime: 2020-07-28 09:44:21
 * @Description: Nuxt测试版
 */

const Service = require('egg').Service;
const moment = require('moment');
class ArtService extends Service {
    async findArtById(id) {
        const art = await this.app.mysql.get("yui_article", {
            id: id,
        })
        return art;
    }
    async createArt(data) {
        const updatetimes = moment().format('YYYY-MM-DD hh-mm-ss')
        const isExsit = await this.app.mysql.get("yui_article", {
            id: data.Tid
        })
        let result, id, mod
        if (!!isExsit) {
            const row = {
                title: data.title,
                articleData: data.articleData,
                updateTm: updatetimes
            };
            const options = {
                where: {
                    id: data.Tid
                }
            };
            mod = 2
            id = data.Tid
            result = await this.app.mysql.update('yui_article', row, options);
        } else {
            const conn = await this.app.mysql.beginTransaction();
            try {
                result = await conn.insert("yui_article", {
                    userId: data.userId,
                    title: data.title,
                    articleData: data.articleData,
                    articleStatus: '0',
                    createTm: updatetimes,
                    updateTm: updatetimes
                })
                id = await conn.get("yui_article", {
                    userId: data.userId,
                    title: data.title
                })
                mod = 1
                conn.commit();
            } catch (err) {
                await conn.rollback(); // 一定记得捕获异常后回滚事务！！
                throw err;
            }

        }

        return {
            id:id.id,
            result,
            mod
        };
    }
    //查询我的文章列表
    async findMy(userid, page) {
        const result = this.app.mysql.select('yui_article', {
            where: {
                userid: userid
            },
            columns: ['id', 'userid', 'title', 'articleStatus', 'updateTm', 'createTm'],
            orders: [
                ['id', 'desc']
            ],
            limit: 6,
            offset: 10 * (page - 1)
        })
        return result
    }
    //删除我的文章
    async deleteMyArticle(userid, id) {
        const result = this.app.mysql.delete('yui_article', {
            userid: userid,
            id: id
        })
        return result
    }
}

module.exports = ArtService;